<template>
  <div class="h100vh w-100% flex flex-col">
    <van-nav-bar :title="route.meta.title" left-text="返回" left-arrow fixed z-index="999" left-disabled
      @click-right="rightClick">
      <template #left>
        <div class="p5px" @click="handleBack">
          <van-icon name="arrow-left" size="22" />
        </div>
        <div v-if="route.path != Store.firstRoute" class="ml15px" @click="closeApp">关闭
        </div>
      </template>
      <template #right>
        <van-icon name="replay" size="22" />
      </template>
    </van-nav-bar>
    <div class="flex-1 overflow-auto" style="padding-top: var(--van-nav-bar-height);box-sizing: border-box;" >
      <router-view></router-view>
    </div>
  </div>
</template>

<script setup>
import { useUserStore, settingConfigStore } from '@/stores'
const Store = useUserStore()
const settingStore = settingConfigStore()
const route = useRoute()
const router = useRouter()
const _env = ref("")
const rightClick = () => {
  // 如果当前路由是首次路由，保持首次路由不变
  if (route.path === Store.firstRoute) {
    Store.updateIsRefresh(false);
  } else {
    Store.updateIsRefresh(true); // 刷新后记录新的首次路由
  }
  // 刷新页面
  location.reload();
};
const handleBack = () => {
  // 如果当前路由是首次路由，调用 closeApp
  if (route.path === Store.firstRoute) {
    closeApp();
  } else {
    router.back(); // 否则正常返回
  }
};

onMounted(() => {
  if (!Store.isRefresh) {
    Store.updatefirstRoute("")
    if (!Store.firstRoute) {
      Store.updatefirstRoute(route.path)
    }
  }

  if (route.query.appFromPath) {
    Store.updateReturnUrl(route.query.appFromPath)
  }
  uni.getEnv(function (res) {
    _env.value = res.h5 ? 'h5' : 'app';
    sendMsg("onIframeLoaded");
  });
  window.addEventListener('message', function (e) {
    if (e.data.action == 'config') {
      settingStore.setConfigInfo(e.data.data)
    }
    console.log("子应用收到APP消息", e.data.action, e.data.data)
  });


  // uni.postMessage({
  //   data: {
  //     action: 'Message'
  //   }
  // });
})

// 发送消息
const sendMsg = (action) => {
  if (!window.parent) {
    return;
  }
  if (_env.value === "h5") {
    window.parent.postMessage({
      data: {
        action: action
      }
    }, "*");
  } else {
    uni.postMessage({
      data: {
        action: action
      }
    });
  }

}
onUnmounted(() => {
  document.removeEventListener('UniAppJSBridgeReady');
})
const closeApp = () => {
  uni.switchTab(
    {
      url: Store.returnUrl
    }
  );
  Store.updateReturnUrl("index")

  setTimeout(() => {
    Store.updatefirstRoute("")
  }, 500)
}
</script>

<style lang="scss" scoped>
:deep(.van-nav-bar__left) {
  padding: 0 10px !important;
}
</style>